package cn.ecnu.search.service.impl;

import cn.ecnu.search.model.AuthorModel;
import cn.ecnu.search.model.FieldModel;
import cn.ecnu.search.model.PaperModel;
import cn.ecnu.vo.message.PaperMessage;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RabbitListener(queues = "paper.add.queue")
public class MessageService {

    @Autowired
    private ElasticsearchOperations operations;

    @RabbitHandler
    public void handleModel(Message msg, PaperMessage message, Channel channel) throws IOException {
        long tag = msg.getMessageProperties().getDeliveryTag();
        String id = null;
        try {
            log.info(message.getPaperId() + "已经收到, 正在处理");
            PaperModel paperModel = new PaperModel();
            BeanUtils.copyProperties(message, paperModel);

            if (message.getAuthors() != null) {
                List<AuthorModel> authors = message.getAuthors().stream().map((author) -> {
                    AuthorModel authorModel = new AuthorModel();
                    BeanUtils.copyProperties(author, authorModel);
                    return authorModel;
                }).collect(Collectors.toList());
                paperModel.setAuthors(authors);
            }

            if (message.getFields() != null) {
                List<FieldModel> fields = message.getFields().stream().map((field) -> {
                    FieldModel fieldModel = new FieldModel();
                    fieldModel.setFieldId(field.getFieldId());
                    fieldModel.setFieldName(field.getFieldName());
                    return fieldModel;
                }).collect(Collectors.toList());
                paperModel.setFields(fields);
            }

            IndexQuery index = new IndexQueryBuilder()
                    .withId(paperModel.getPaperId().toString())
                    .withObject(paperModel)
                    .build();
            id = operations.index(index, IndexCoordinates.of("paper"));
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicReject(tag, true);
        }

        if (!StringUtils.isEmpty(id)) channel.basicAck(tag, false);
        else channel.basicReject(tag, true);
    }
}
